{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5b04393e",
   "metadata": {},
   "source": [
    "# 什么是模块？\n",
    "将模块视为与代码库相同。\n",
    "\n",
    "一个文件，其中包含要包含在应用程序中的一组函数。\n",
    "\n",
    "# 创建模块\n",
    "要创建模块，只需将所需的代码保存在文件扩展名为 .py 的文件中："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e3a78289",
   "metadata": {},
   "outputs": [],
   "source": [
    "# %load mymodule.py\n",
    "person1 = {\n",
    "  \"name\": \"John\",\n",
    "  \"age\": 36,\n",
    "  \"country\": \"Norway\"\n",
    "}\n",
    "\n",
    "def greeting(name):\n",
    "  print(\"Hello, \" + name)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d14100c6",
   "metadata": {},
   "source": [
    "# 使用模块\n",
    "现在我们可以使用我们刚刚创建的模块，通过使用 import 语句："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c7bc22a5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, Jonathan\n"
     ]
    }
   ],
   "source": [
    "import mymodule\n",
    "\n",
    "mymodule.greeting(\"Jonathan\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79845ba3",
   "metadata": {},
   "source": [
    "# 模块中的变量\n",
    "模块可以包含已经描述过的函数，也可以包含所有类型的变量（数组、字典、对象等）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e8af7a23",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "36\n"
     ]
    }
   ],
   "source": [
    "a = mymodule.person1[\"age\"]\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5c9593a",
   "metadata": {},
   "source": [
    "# 从模块导入\n",
    "可以使用 from 关键字选择仅从模块导入部分内容。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "049a1ed5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "36\n"
     ]
    }
   ],
   "source": [
    "from mymodule import person1\n",
    "\n",
    "print (person1[\"age\"])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.10"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
